package com.yiba.logutils.save.impl;

import android.content.Context;

import com.yiba.logutils.YBLogConstants;
import com.yiba.logutils.save.ILogWriter;
import com.yiba.logutils.utils.DateUtils;
import com.yiba.logutils.utils.Logs;

import java.io.File;
import java.util.concurrent.atomic.AtomicBoolean;

public class MmapLogWriter implements ILogWriter{

    static {
        try {
            System.loadLibrary("memlog-lib");
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }

    private native long nativeInit(String basicInfo, String dir, String key);

    private native long nativeWrite(long logWriterObject, String msgContent, boolean encryptFlag);

    //刷新用户后，需要更新基础信息
    private native void nativeRefreshBasicInfo(long logWriterObject, String basicInfo);

    private native void nativeCloseAndRenew(long logWriterObject);

    private final AtomicBoolean initFlag = new AtomicBoolean(false);
    //C++ LogWriter对象的句柄
    private long nativeLogWriter;
    private String logFileDir;
    private String buildDate;
    private File logFile;
    @Override
    public void init(Context context, String basicInfoContent, String dir, String key) throws Throwable {
        Logs.i("MmapWriter", "MMapLogWriter-->init");
        logFileDir = dir;
        buildDate = DateUtils.getDate();
        nativeLogWriter = nativeInit(basicInfoContent, dir, key);
        initFlag.set(true);
        logFile = new File(logFileDir + File.separator + buildDate + YBLogConstants.MMAP);
    }

    @Override
    public void write(String content, boolean encryptFlag) throws Throwable {
        if (nativeLogWriter <= 0) {
            Logs.i("nativeLogWriter is null,return");
            return;
        }
        if (!initFlag.get()) {
            Logs.i("has not been init");
            return;
        }
        // 判断写入的时候日期是否是当天，判断日志文件是否存在
        if (!DateUtils.getDate().equals(buildDate) || !isLogFileExist()) {
            // 确保文件目录存在，以防被手动删除
            File dir = new File(logFileDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            buildDate = DateUtils.getDate();
            closeAndRenew();
            logFile = new File(logFileDir + File.separator + buildDate + YBLogConstants.MMAP);
        }
        nativeWrite(nativeLogWriter, content, encryptFlag);
    }

    @Override
    public void refreshBasicInfo(String basicInfo) {
        Logs.i("MmapWriter", "MmapLogWriter-->refreshBasicInfo");
        if (nativeLogWriter <= 0) {
            return;
        }
        nativeRefreshBasicInfo(nativeLogWriter, basicInfo);
    }

    @Override
    public void closeAndRenew() {
        if (nativeLogWriter <= 0) {
            return;
        }
        nativeCloseAndRenew(nativeLogWriter);
    }

    @Override
    public boolean isLogFileExist() {
        return logFile != null && logFile.exists();
    }
}
